//
//  HistoryDataViewController.m
//  SHHCPhone
//
//  Created by gfsh on 14-6-18.
//  Copyright (c) 2014年 sheng long. All rights reserved.
//

#import "HistoryDataViewController.h"
//#import "ChartView.h"
#import "GraphView.h"

@implementation HistoryDataViewController
{
    NSMutableArray *styleBtns;
    NSMutableArray *typeBtns;
    NSMutableArray *typeLabs;
    
    NSInteger typeIndex;
    NSInteger styleIndex;
    
    NSArray *types;
    NSArray *styles;
    
    NSString *currentDate;

    NSMutableArray *data;
    
    UILabel *dateFieldLab;
    
    NSDate *currentWeekDate;
    NSDate *currentMonthDate;
    NSDate *currentYearDate;
    
    GraphView *gv;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    navigationBarView.title = @"历史数据";
    [navigationBarView setNormalLeftMenuButton];
    [navigationBarView setNormalRightButton];

    [self initTagBtns];
    [self initChart];
    [self initCircleBtn];
    
    typeIndex = 0;

//    currentWeekDate = currentMonthDate = currentYearDate = [NSDate date];
    
    currentWeekDate = [NSDate date];
    currentMonthDate = [z_DateTime dencodeTime2:[NSString stringWithFormat:@"%@-01",[z_DateTime encodeTime:[NSDate date] format:@"yyyy-MM"]]];
    currentYearDate = [z_DateTime dencodeTime2:[NSString stringWithFormat:@"%@-01-01",[z_DateTime encodeTime:[NSDate date] format:@"yyyy"]]];
    
    [self styleBtnClick:styleBtns[0]];
    
}

#pragma mark 初始化标签按钮
- (void)initTagBtns
{
    styleBtns = [NSMutableArray array];
    styles = @[kStyleWeek,kStyleMonth,kStyleYear];
    NSArray *titles = @[@"周",@"月",@"年"];
    NSArray *directions = @[@"左",@"中",@"右"];
    for (NSString *title in titles) {
        NSInteger index = [titles indexOfObject:title];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = index;
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        btn.frame = CGRectMake(9+index*(CURRENT_CONTENT_WIDTH-18)/3, NAVIGATIONBAR_HEIGHT+9, (CURRENT_CONTENT_WIDTH-18)/3, 27);
        [btn setTitle:titles[index] forState:UIControlStateNormal];
        [btn setTitleColor:GET_COLOR(@"fe8cb6") forState:UIControlStateNormal];
        [btn setTitleColor:GET_COLOR(@"ffffff") forState:UIControlStateSelected];
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"标签-%@-未选中",directions[index]]] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"标签-%@-未选中",directions[index]]] forState:UIControlStateHighlighted];
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"标签-%@-选中",directions[index]]] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(styleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        [styleBtns addObject:btn];
    }
}

#pragma mark 初始化图标
- (void)initChart
{
    gv = [[GraphView alloc]initWithFrame:CGRectMake(9, NAVIGATIONBAR_HEIGHT+9+27+15+30, CURRENT_CONTENT_WIDTH-19, CURRENT_CONTENT_HEIGHT-NAVIGATIONBAR_HEIGHT-9-27-15-30-120)];
    gv.cellWidth = 40.f;
    gv.cellHeight = (gv.frame.size.height-70)/3;
    //gv.title = @"体重及体成份";
    gv.titleColor = GET_COLOR(@"fe8cb6");
    [self.view addSubview:gv];
    
    UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(9, gv.frame.origin.y-30, gv.frame.size.width, 30)];
    bg.backgroundColor = GET_COLOR(@"feaecc");
    [self.view addSubview:bg];
    
    UIButton *leftArrow = [UIButton buttonWithType:UIButtonTypeCustom];
    leftArrow.tag = 0;
    leftArrow.contentEdgeInsets = UIEdgeInsetsMake(5, 14, 5, 14);
    leftArrow.frame = CGRectMake(0, 0, 48, 30);
    [leftArrow setImage:[UIImage imageNamed:@"历史数据-左箭头默认"] forState:UIControlStateNormal];
    [leftArrow setImage:[UIImage imageNamed:@"历史数据-左箭头点击"] forState:UIControlStateHighlighted];
    [leftArrow addTarget:self action:@selector(arrowClick:) forControlEvents:UIControlEventTouchUpInside];
    [bg addSubview:leftArrow];
    
    dateFieldLab = [[UILabel alloc]initWithFrame:CGRectMake(48, 0, bg.frame.size.width-48*2, 30)];
    dateFieldLab.backgroundColor = [UIColor clearColor];
    dateFieldLab.textAlignment = NSTextAlignmentCenter;
    dateFieldLab.textColor = GET_COLOR(@"ffffff");
    dateFieldLab.font = [UIFont systemFontOfSize:14];
    //dateFieldLab.text = @"07月14日 - 07月20日";
    [bg addSubview:dateFieldLab];
    
    UIButton *rightArrow = [UIButton buttonWithType:UIButtonTypeCustom];
    rightArrow.tag = 1;
    rightArrow.contentEdgeInsets = UIEdgeInsetsMake(5, 14, 5, 14);
    rightArrow.frame = CGRectMake(bg.frame.size.width-48, 0, 48, 30);
    [rightArrow setImage:[UIImage imageNamed:@"历史数据-右箭头默认"] forState:UIControlStateNormal];
    [rightArrow setImage:[UIImage imageNamed:@"历史数据-右箭头点击"] forState:UIControlStateHighlighted];
    [rightArrow addTarget:self action:@selector(arrowClick:) forControlEvents:UIControlEventTouchUpInside];
    [bg addSubview:rightArrow];
}

#pragma mark 初始化分类圆按钮
- (void)initCircleBtn
{
    CGFloat blankWidth = (CURRENT_CONTENT_WIDTH/4 - 65)/2;
    CGFloat labWidth = CURRENT_CONTENT_WIDTH/4;
    
    typeBtns = [NSMutableArray array];
    typeLabs = [NSMutableArray array];
    types = @[kTypeWeight,kTypeFat,kTypeMuscle,kTypeWater];
    
    NSArray *titles = @[@"体重",@"体脂率",@"肌肉量",@"水分"];

    for (NSString *title in titles) {
        NSInteger index = [titles indexOfObject:title];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = index;
        btn.frame = CGRectMake(blankWidth*(index+1)+index*(65+blankWidth), gv.frame.origin.y+gv.frame.size.height+15, 65, 65);
        [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"历史数据页-%@icon",titles[index]]] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"历史数据页-%@icon-点击",titles[index]]] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(typeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(index*labWidth, btn.frame.origin.y+btn.frame.size.height, labWidth, 35)];
        lab.textAlignment = NSTextAlignmentCenter;
        lab.textColor = GET_COLOR(@"3e3e3e");
        lab.font = [UIFont systemFontOfSize:14];
        lab.text = titles[index];
        [self.view addSubview:btn];
        [self.view addSubview:lab];
        [typeBtns addObject:btn];
        [typeLabs addObject:lab];
    }
}

#pragma mark 周期选择按钮事件
//标签按钮事件
- (void)styleBtnClick:(UIButton*)btn
{
    for (UIButton *styleBtn in styleBtns) {
        if ([styleBtn isEqual:btn]) {
            styleBtn.selected = YES;
        }else{
            styleBtn.selected = NO;
        }
    }
    styleIndex = btn.tag;
    [self setDateFieldTextForward:-1];
    [self typeBtnClick:typeBtns[typeIndex]];
}

#pragma mark 体成分分类选择事件
- (void)typeBtnClick:(UIButton*)btn
{
    for (UIButton *typeBtn in typeBtns) {
        NSInteger index = [typeBtns indexOfObject:typeBtn];
        UILabel *lab = [typeLabs objectAtIndex:index];
        if ([typeBtn isEqual:btn]) {
            typeBtn.selected = YES;
            lab.textColor = GET_COLOR(@"fe8cb6");
        }else{
            typeBtn.selected = NO;
            lab.textColor = GET_COLOR(@"3e3e3e");
        }
    }
    typeIndex = btn.tag;
    
    [self loadDataWithType:types[typeIndex] andStyle:styles[styleIndex] andStartDate:[self currentDateStrAtStyleIndex]];
}

- (NSString*)currentDateStrAtStyleIndex
{
    NSDate *sdate = currentWeekDate;
    
    switch (styleIndex) {
        case 1:
            sdate = currentMonthDate;
            break;
        case 2:
            sdate = currentYearDate;
        default:
            sdate = currentWeekDate;
            break;
    }
    return [z_DateTime encodeTime:sdate format:@"yyyyMMdd"];
}

#pragma mark 箭头点击事件

- (void)arrowClick:(UIButton*)btn
{
    BOOL flag = NO;
    switch (styleIndex) {
        case 0:
            flag = [z_DateTime nowIsInFieldFrom:currentWeekDate to:[z_DateTime dateOffsetDays:6 fromDate:currentWeekDate]];
            break;
        case 1:
            flag = [z_DateTime nowIsInFieldFrom:currentMonthDate to:[z_DateTime dencodeTime2:[z_DateTime nextMonthOfDate:currentMonthDate forward:YES]]];
            break;
        case 2:
            flag = [z_DateTime nowIsInFieldFrom:currentYearDate to:[z_DateTime dencodeTime2:[NSString stringWithFormat:@"%d-01-01",[[z_DateTime encodeTime:currentYearDate format:@"yyyy"]integerValue]+1]]];
            break;
        default:
            break;
    }

    if (btn.tag&&flag) {
        [LoadingFrameView autoDisappearBlockingview:@"只能查看今天之前的数据"];
        return;
    }
    [self setDateFieldTextForward:btn.tag];
    [self loadDataWithType:types[typeIndex] andStyle:styles[styleIndex] andStartDate:[self currentDateStrAtStyleIndex]];
}

- (void)setDateFieldTextForward:(NSInteger)forward
{
    NSString *startDateStr = nil,*endDateStr = nil;
    switch (styleIndex) {
        case 0:
        {
            NSDate *date = currentWeekDate;
            if (forward!=-1) {
                date = [z_DateTime dateOffsetDays:forward?7:-7 fromDate:currentWeekDate];
            }
            NSInteger index =  [z_DateTime indexOfWeekAtDate:date];
            NSInteger sDays = 0,eDays = 0;
            sDays = index == 1?-6:(index==2?0:2-index);
            eDays = index == 1?0:(index==2?6:8-index);
            NSDate *sdate = [z_DateTime dateOffsetDays:sDays fromDate:date];
            NSDate *edate = [z_DateTime dateOffsetDays:eDays fromDate:date];
            startDateStr = [z_DateTime encodeTime:sdate format:@"MM月dd日"];
            endDateStr = [z_DateTime encodeTime:edate format:@"MM月dd日"];
            currentWeekDate = sdate;
        }
            break;
        case 1:
        {
            NSString *dateStr = [z_DateTime encodeTime:currentMonthDate format:@"yyyy-MM-dd"];
            NSString *sDateStr = dateStr;
            if (forward==0) {
                sDateStr = [z_DateTime nextMonthOfDate:currentMonthDate forward:NO];
                startDateStr = [z_DateTime encodeTime:[z_DateTime dencodeTime2:sDateStr] format:@"yyyy年MM月"];
                endDateStr = [z_DateTime encodeTime:[z_DateTime dencodeTime2:dateStr] format:@"yyyy年MM月"];
            }else if (forward==1) {
                sDateStr = [z_DateTime nextMonthOfDate:currentMonthDate forward:YES];
                startDateStr = [z_DateTime encodeTime:[z_DateTime dencodeTime2:sDateStr] format:@"yyyy年MM月"];
                endDateStr = [z_DateTime encodeTime:[z_DateTime dencodeTime2:[z_DateTime nextMonthOfDate:[z_DateTime dencodeTime2:sDateStr] forward:YES]] format:@"yyyy年MM月"];
            }else{
                startDateStr = [z_DateTime encodeTime:[z_DateTime dencodeTime2:sDateStr] format:@"yyyy年MM月"];
                endDateStr = [z_DateTime encodeTime:[z_DateTime dencodeTime2:[z_DateTime nextMonthOfDate:currentMonthDate forward:YES]] format:@"yyyy年MM月"];
            }
            currentMonthDate = [z_DateTime dencodeTime2:sDateStr];
        }
            break;
        case 2:
        {
            NSString *yearStr = [z_DateTime encodeTime:currentYearDate format:@"yyyy"];
            NSString *sYearStr = yearStr;
            if (forward==0) {
                sYearStr = [NSString stringWithFormat:@"%d",[yearStr integerValue]-1];
                startDateStr = [NSString stringWithFormat:@"%@年",sYearStr];
                endDateStr = [NSString stringWithFormat:@"%@年",yearStr];
            }else if (forward==1){
                sYearStr = [NSString stringWithFormat:@"%d",[yearStr integerValue]+1];
                startDateStr = [NSString stringWithFormat:@"%@年",sYearStr];
                endDateStr = [NSString stringWithFormat:@"%d年",[sYearStr integerValue]+1];
            }else{
                startDateStr = [NSString stringWithFormat:@"%@年",sYearStr];
                endDateStr = [NSString stringWithFormat:@"%d年",[sYearStr integerValue]+1];
            }
            currentYearDate = [z_DateTime dencodeTime:[NSString stringWithFormat:@"%@-01-01",sYearStr] format:@"yyyy-MM-dd"];
        }
            break;
        default:
            break;
    }
    
    if (startDateStr&&endDateStr) {
        dateFieldLab.text = [NSString stringWithFormat:@"%@ - %@",startDateStr,endDateStr];
    }
}

#pragma mark 画线条
- (void)drawChart
{
    NSMutableArray *lines = [NSMutableArray array];
    
    for (NSDictionary *style in data) {
        NSDictionary *type = [style objectForKey:styles[styleIndex]];
        NSArray *arr = [type objectForKey:types[typeIndex]];
        if (arr) {
            NSMutableArray *xAsis = [NSMutableArray array];
            NSMutableArray *yAsis = [NSMutableArray array];
            NSMutableArray *points = [NSMutableArray array];
            CurveLine *line = [[CurveLine alloc]init];
            
            CGFloat min = -1,max = -1;
            NSString *unit = nil;
            for (NSDictionary *sdic in arr) {
                CGFloat y = [(NSString*)sdic[@"y"] floatValue];
                if (!unit) {
                    unit = (NSString*)sdic[@"unit"];
                }
                if (min == -1) {
                    min = y;
                }else{
                    min = MIN(min, y);
                }
                
                if (max == -1) {
                    max = y;
                }else{
                    max = MAX(max, y);
                }
            }
            
            CGFloat zMin = floor(min),zMax = ceil(max),zAvg = (zMax-zMin)/(4-1);
            if ([unit isEqualToString:@"%"]) {
                if (zAvg == 0) {
                    zAvg = 33.3;
                    zMax = 100;
                }else{
                    zMax = zMin+zAvg*3;
                }
            }
            if ([unit isEqualToString:@"kg"]) {
                if (zAvg == 0) {
                    zAvg = 0.33;
                    zMax = 1.f;
                }else{
                    zMax = zMin+zAvg*3;
                }
            }
            [yAsis addObject:[NSString stringWithFormat:@"%.1f%@",zMin,unit]];
            [yAsis addObject:[NSString stringWithFormat:@"%.1f%@",zMin+zAvg,unit]];
            [yAsis addObject:[NSString stringWithFormat:@"%.1f%@",zMin+zAvg*2,unit]];
            [yAsis addObject:[NSString stringWithFormat:@"%.1f%@",zMax,unit]];
            //[yAsis addObject:[NSString stringWithFormat:@"%@%@",(NSString*)sdic[@"y"],(NSString*)sdic[@"unit"]]];
            
            for (NSDictionary *sdic in arr) {
                NSInteger index = [arr indexOfObject:sdic];
                [xAsis addObject:[NSString stringWithFormat:@"%@",sdic[@"x"]]];
                CGPoint p = CGPointMake(index, ([sdic[@"y"] floatValue]+0.0001)/zAvg);
                [points addObject:NSStringFromCGPoint(p)];
            }
            line.points = points;
            gv.xAsis = xAsis;
            gv.yAsis = yAsis;
            [lines addObject:line];
        }
    }
    
    gv.frontLineIndex = 0;

    for (CurveLine *cl in lines) {
//        NSInteger idx = [lines indexOfObject:cl];
//        cl.lineColor = GET_COLOR(@"e8e8e8");
//        if (idx == typeIndex) {
            cl.lineColor = GET_COLOR(@"fe8cb6");
//        }
    }
    gv.data = lines;
}

#pragma mark 加载数据
-(void)loadDataWithType:(NSString*)type andStyle:(NSString*)style andStartDate:(NSString*)sdate
{
    CLog(@"获取历史数据");
    
    NSMutableDictionary *dic= [NSMutableDictionary dictionary];
    [dic setValue:IOS_HISTORY forKeyPath:IOS_METHOD_NAME];
    [dic setValue:APP_USER_MSG.id forKeyPath:kUserID];
    if (type) {
        [dic setObject:type forKey:kType];
    }
    if (style) {
        [dic setObject:style forKey:kStyle];
    }
    if (sdate) {
        [dic setObject:sdate forKey:kStartDate];
    }

    data = [NSMutableArray array];
    [LoadingFrameView showLoadingview];

    ASIHTTPRequest *request =  [NetUtls httpGet:self withValue:dic tag:IOS_HISTORY_TAG+typeIndex need:YES];
    [request startAsynchronous];

}

-(void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%d:%@",request.tag,[request responseString]);
    NSArray *arr = [[request responseString] objectFromJSONString];

    //获取历史数据
    if (arr != nil) {
        [data removeAllObjects];
        [data addObject:@{styles[styleIndex]:@{types[request.tag%IOS_HISTORY_TAG]:arr}}];
    }else{
        [self requestFailed:request];
    }
    

    [LoadingFrameView directlyDisappear];
    if (data.count) {
        //[self typeBtnClick:typeBtns[typeIndex]];
        [self drawChart];
    }

    
}

-(void)requestFailed:(ASIHTTPRequest *)request
{
//    [LoadingFrameView autoDisappearBlockingview:[NSString stringWithFormat:@"获取%d失败",request.tag]];
    [LoadingFrameView autoDisappearBlockingview:@"获取失败"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
